<?php

namespace App\Store\Controllers\OldMaterial;

use App\Common\Services\CommonExcelExport;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\OldMaterial\ReturnFactory;
use App\Store\Models\OldMaterial\ReturnFactoryInfolist;
use App\Store\Models\OldMaterial\Log;
use App\Store\Models\OldMaterial\Stock;
use App\Store\Models\OldMaterial\TotalStock;
use App\Store\Services\Goods\Goods;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Validate\OldMaterial\ReturnFactory as ValidateOldMaterialReturnFactory;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 返厂
 */
class ReturnController extends Controller
{
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['target_store_id', 'remark', 'oldmaterial_list']);
        $Validate = new ValidateOldMaterialReturnFactory();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $start_store_id = $accountinfo['store_ids'];

        //处理调拨旧料列表
        $oldmaterial_list = $req_data['oldmaterial_list'];
        $oldmaterial_info_data = is_array($oldmaterial_list) ? $oldmaterial_list : (is_array(json_decode($oldmaterial_list, true)) ? json_decode($oldmaterial_list, true) : []);

        $goods_count = array_sum(array_column($oldmaterial_info_data,'count'));

        DB::beginTransaction();
        try {
            $order_sncode = StoreCommon::createOrderSn();
            $oldmaterial_data = [
                'cp_id' => $cp_id,
                'start_store_id' => $start_store_id,
                'target_store_id' => $req_data['target_store_id'],
                'order_sncode' => $order_sncode,
                'goods_count' => $goods_count,
                'remark' => $req_data['remark'],
                'create_account_id' => $accountinfo['id'],
                'create_account_real_name' => $accountinfo['real_name'],
                'create_at' => time(),
            ];

            //调拨单
            $oldmaterial_id = ReturnFactory::create($oldmaterial_data)->id;

            $logs =[];
            $ids = array_column($oldmaterial_info_data,'id');

            $stockList = Stock::query()
                ->where(['cp_id' => $cp_id, 'store_id' => $start_store_id])
                ->whereIn('id', $ids)
                ->get()
                ->pluck(null, 'id')
                ->toArray();

            $returnArr=[];
            if ($oldmaterial_info_data) {
                foreach ($oldmaterial_info_data as $k => $v) {
                    // 追加
                    $stock = $stockList[$v['id']] ?? [];
                    $arr = $this->checkReturn($stock, $v, false,1);

                    $v['audit_status'] = 1;
                    $v['stock_id'] = $v['id'];
                    $v['start_store_id'] = $start_store_id;
                    $v['target_store_id'] = $req_data['target_store_id'];
                    $v['order_sncode'] = $order_sncode;
                    $v['cp_id'] = $cp_id;
                    $v['p_id'] = $oldmaterial_id;
                    $v['create_account_id'] = $accountinfo['id'];
                    $v['create_account_real_name'] = $accountinfo['real_name'];
                    $v['create_at'] = time();
                    //删除不需要的字段
                    unset($v['id'], $v['goods_brand'], $v['goods_pricetype'],$v['goods_category'], $v['storeinfo'], $v['type'], $v['dold_fee'],$v['valuations']);


                    //更新旧料库存状态stock_status改为返厂,重新计算实重
                    if (!empty($stock)) {
                        $stockData = $this->checkReturn($stock, $v, false);
                        $stockData['stock_status'] = 4;
                        $stockData['update_at'] = time();
                        $v['total_cost_fee'] = $stockData['deduct_total_cost_fee'];
                        $stockData['total_cost_fee'] =$stockData['remaining_cost_fee'];
                        $stockData['update_at'] = time();
                        unset($stockData['deduct_total_cost_fee'], $stockData['remaining_cost_fee']);
                        Stock::query()->where('id',$v['stock_id'])->update($stockData);
                    }

                    $returnArr[] = array_merge($v,$arr);

                }
                $logs[] =[
                    'cp_id' => $cp_id,
                    'store_id' => $v['store_id'],
                    'start_store_id' => $start_store_id,
                    'target_store_id' => $req_data['target_store_id'],
                    'order_sncode' => $order_sncode,
                    'goods_category_id' => $v['goods_category_id'],
                    'piece_weight' => $v['piece_weight'],
                    'stock_type' => $v['stock_type'],
                    'count' => $v['count'],
                    'cf_no' => $v['cf_no'],
                    'log_type' => 5,
                    'create_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                ];
            }

            if(!empty($returnArr)){
                ReturnFactoryInfolist::query()->insert($returnArr);
            }
            if(!empty($logs)) {
                Log::query()->insert($logs);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '添加失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '添加成功']);
    }

    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $list = ReturnFactory::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        //不分页
        $request['isgetall'] = 1;
        $list = ReturnFactory::getList($request)['list'];

        $row = [
            ['table_header'=>'旧料返厂'],
            [
                'start_store_name' => '起始门店',
                'target_store_name' => '目的门店',
                'order_sncode' => '调拨单号',
                'audit_status' => '订单状态',
                'goods_count' => '数量',
                'create_account_real_name' => '创建人',
                'create_at' => '创建时间',
            ]];

        foreach ($list as $item){
            $exceldata[] =[
                'start_store_name'=>$item['startstoreinfo']['store_name']?? '',
                // 写死
                'target_store_name'=>'财务部',
                'order_sncode'=>$item['order_sncode'],
                'audit_status'=>$item['audit_status']==1? '待审核':($item['audit_status']==2?'审核中':'审核'),
                'goods_count'=>$item['goods_count'],
                'create_account_real_name'=>$item['create_account_real_name']?? '',
                'create_at'=>date('Y-m-d H:i:s',$item['create_at']),
            ];

        }


//        if ($list['list']) {
//            $ids = [];
//            foreach ($list['list'] as $v) {
//                $ids[] = $v['id'];
//            }
//
//            $infolist = ReturnFactoryInfolist::with('startstoreinfo', 'targetstoreinfo', 'goods_category', 'goods_brand')->whereIn('p_id', $ids)->get()->toArray();
//
//            $row = [
//                ['table_header'=>'旧料返厂'],
//                [
//                'start_store_name' => '起始门店',
//                'target_store_name' => '目的门店',
//                'order_sncode' => '订单号',
//                'create_at' => '回收时间',
//                'stock_type' => '回收方式',
//                'goods_sn_code' => '条码',
//                'goods_category_id' => '旧料类别',
//                'count' => '数量',
//                'piece_weight' => '重量',
//                'piece_weight_new' => '实重',
//                'cf_no' => '证书号',
//                'goods_brand_id' => '品牌',
//                'goods_pricetype_id' => '价格类型',
//                'main_stone_weigth' => '主石重',
//                'main_stone_count' => '主石数',
//                'other_stone_weigth' => '副石重',
//                'other_stone_count' => '副石数',
//                'color' => '颜色',
//                'clarity' => '净度',
//                'exchange_amount' => '换货金额',
//            ]];
//
//            $exceldata = [];
//            foreach ($infolist as $val) {
//                $exceldata[] = [
//                    'start_store_name' => $val['startstoreinfo']?$val['startstoreinfo']['store_name']:'',
//                    'target_store_name' => $val['targetstoreinfo']?$val['targetstoreinfo']['store_name']:'',
//                    'order_sncode' => $val['order_sncode'],
//                    'create_at' => date('Y-m-d H:i:s', $val['create_at']),
//                    'stock_type' => ($val['stock_type'] == 1) ? '按克' : '标价',
//                    'goods_sn_code' => $val['goods_sn_code'],
//                    'goods_category_id' => $val['goods_category']['category_name'] ?? '',
//                    'count' => $val['count'],
//                    'piece_weight' => $val['piece_weight'],
//                    'piece_weight_new' => $val['piece_weight_new'],
//                    'cf_no' => $val['cf_no'],
//                    'goods_brand_id' => $val['goods_brand']['brand_name'] ?? '',
//                    'goods_pricetype_id' => '价格类型',
//                    'main_stone_weigth' => $val['main_stone_weigth'],
//                    'main_stone_count' => $val['main_stone_count'],
//                    'other_stone_weigth' => $val['other_stone_weigth'],
//                    'other_stone_count' => $val['other_stone_count'],
//                    'color' => $val['color'],
//                    'clarity' => $val['clarity'],
//                    'exchange_amount' => $val['exchange_amount'],
//                ];
//            }

           // $filename = '旧料返厂信息导出_' . time() . '.xlsx';
           // return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
       // }
        $filename = '旧料返厂信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata,[],[],false), $filename);
    }

    /**
     * 详情
     */
    public function getinfolist(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = ReturnFactory::with(['startstoreinfo'])->where(['id' => $id, 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $info['total_count_new'] = ReturnFactoryInfolist::where(['p_id' => $id, 'cp_id' => $cp_id])->select(DB::raw('sum(count) as count'))->first()->toArray()['count'];

        $where = [];
        $order_sncode = $request->order_sncode ?? '';
        if ($order_sncode != '') {
            $where[] = ['order_sncode', 'like', '%' . $order_sncode . '%'];
        }

        $goods_category_id = $request->goods_category_id ?? 0;
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
        }

        $audit_status = $request->audit_status ?? 0;

        //按照类别汇总
        $list1 = ReturnFactoryInfolist::with(['goods_category'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where)
            ->groupBy('goods_category_id')
            ->select('goods_category_id', DB::raw('sum(count) as count,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(piece_weight) as piece_weight,sum(piece_weight_new) as piece_weight_new,sum(exchange_amount) as exchange_amount'))
            ->get()->toArray();
        if ($list1) {
            foreach ($list1 as $k => $v){
                if ($v['audit_failed_count'] + $v['audit_success_count'] >= $v['count']) {
                    $status = 3;
                } elseif ($v['audit_failed_count'] + $v['audit_success_count'] < $v['count']){
                    if ($v['audit_failed_count'] == 0 && $v['audit_success_count'] == 0) {
                        $status = 1;
                    } else {
                        $status = 2;
                    }
                }
                $list1[$k]['audit_status'] = $status;

                if ($audit_status > 0) {
                    if ($status != $audit_status) {
                        unset($list1[$k]);
                    }
                }
            }
            $list1_new = array_values($list1);
        }

        //查询子订单详情
        $list2_query = ReturnFactoryInfolist::with(['storeinfo', 'startstoreinfo', 'targetstoreinfo', 'goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where);
        if ($audit_status > 0) {
            $list2_query->where('audit_status', $audit_status);
        }
        $list2 = $list2_query->get()->toArray();

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info, 'list1' => $list1_new, 'list2' => $list2]]);
    }

    /**
     * 汇总导出
     */
    public function dosummaryexport(Request $request)
    {
        $id = $request->id ?? 0;
        $ids = $request['ids'];
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = ReturnFactory::where(['id' => $id, 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $where = [];
        $goods_category_id = $request->goods_category_id ?? 0;
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
        }

        $query = ReturnFactoryInfolist::with(['goods_category'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where);

        if (count($ids) > 0) {
            $query->whereIn('goods_category_id', $ids);
        }

        $list = $query->groupBy('goods_category_id')
            ->select('goods_category_id', DB::raw('sum(count) as count,sum(piece_weight) as piece_weight,sum(piece_weight_new) as piece_weight_new,sum(exchange_amount) as exchange_amount'))
            ->get()->toArray();

        $row = [
            ['table_header'=>'旧料返厂-类别汇总'],
            [
            'goods_category_id' => '旧料类别',
            'count' => '件数',
            'piece_weight' => '重量',
            'piece_weight_new' => '实重',
            'exchange_amount' => '换货金额',
        ]];

        $exceldata = [];
        foreach ($list as $val) {
            $exceldata[] = [
                'goods_category_id' => $val['goods_category']['category_name'] ?? '',
                'count' => $val['count'],
                'piece_weight' => $val['piece_weight'],
                'piece_weight_new' => $val['piece_weight_new'],
                'exchange_amount' => $val['exchange_amount']>0? ($val['exchange_amount']/100):0,
            ];
        }

        $filename = '旧料调拨汇总信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    /**
     * 明细导出
     */
    public function doinfolistexport(Request $request)
    {
        $id = $request->id ?? 0;
        $ids = $request['ids'];
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = ReturnFactory::where(['id' => $id, 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $where = [];
        $goods_category_id = $request->goods_category_id ?? 0;
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
        }

        $query = ReturnFactoryInfolist::with(['startstoreinfo', 'targetstoreinfo', 'goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where);

        if (count($ids) > 0) {
            $query->whereIn('id', $ids);
        }
        $list = $query->get()->toArray();

        $row = [
            ['table_header'=>'旧料返厂-返厂明细'],
            [
            'start_store_name'=>'回收门店',
           // 'target_store_name' => '目的门店',
            'order_sncode' => '订单号',
            'create_at' => '回收时间',
            'stock_type' => '回收方式',
            'goods_sn_code' => '条码',
            'goods_category_id' => '旧料类别',
            'count' => '数量',
            'piece_weight' => '重量',
            'piece_weight_new' => '实重',
            'cf_no' => '证书号',
            'goods_brand_id' => '品牌',
            'goods_pricetype_id' => '价格类型',
            'main_stone_weigth' => '主石重',
            'main_stone_count' => '主石数',
            'other_stone_weigth' => '副石重',
            'other_stone_count' => '副石数',
            'color' => '颜色',
            'clarity' => '净度',
            'exchange_amount' => '换货金额',
        ]];

        $exceldata = [];
        foreach ($list as $val) {
            $exceldata[] = [
                'start_store_name'=>$val['startstoreinfo']['store_name']??'',
               // 'target_store_name' => $val['targetstoreinfo']['store_name']?? '',
                'order_sncode' => $val['order_sncode'],
                'create_at' => date('Y-m-d H:i:s', $val['create_at']),
                'stock_type' => ($val['stock_type'] == 1) ? '按克' : '标价',
                'goods_sn_code' => $val['goods_sn_code'],
                'goods_category_id' => $val['goods_category']['category_name'] ?? '',
                'count' => $val['count'],
                'piece_weight' => $val['piece_weight'],
                'piece_weight_new' => $val['piece_weight_new'],
                'cf_no' => $val['cf_no'],
                'goods_brand_id' => $val['brand']['brand_name'] ?? '',
                'goods_pricetype_id' => '价格类型',
                'main_stone_weigth' => $val['main_stone_weigth'],
                'main_stone_count' => $val['main_stone_count'],
                'other_stone_weigth' => $val['other_stone_weigth'],
                'other_stone_count' => $val['other_stone_count'],
                'color' => $val['color'],
                'clarity' => $val['clarity'],
                'exchange_amount' => $val['exchange_amount'] > 0 ? $val['exchange_amount']/100 : 0,
            ];
        }

        $filename = '旧料返厂明细信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    /**
     * 删除
     */
    public function dodel(Request $request)
    {
        $req_data = $request->only(['id']);
        $Validate = new ValidateOldMaterialReturnFactory('del');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);

        $infolist = ReturnFactoryInfolist::query()->where(['p_id'=>$req_data['id'],'cp_id'=>$cp_id])->get()->toArray();

        DB::beginTransaction();
        try {

            if (!empty($infolist)) {
                $stockIds = array_column($infolist, 'stock_id');
                $stockList = Stock::query()
                    ->where(['cp_id' => $cp_id])
                    ->whereIn('id', $stockIds)
                    ->get()
                    ->pluck(null, 'id')
                    ->toArray();



                foreach ($infolist as $v) {
                    $stock = $stockList[$v['stock_id']] ?? [];
                    // 待审核需要退回
                    if (!empty($stock) && $v['audit_status'] == 1) {
                        $stockData = $this->checkReturn($stock, $v, true);
                        $stockData['stock_status'] = 1;
                        $stockData['update_at'] = time();
                        Stock::query()
                            ->where('id', $v['stock_id'])
                            ->where('cp_id', $cp_id)
                            ->where('store_id', $v['start_store_id'])
                            ->update($stockData);
                    }

                }
            }

            ReturnFactory::where('id', $req_data['id'])->update([
                'is_del' => 2,
                'del_at' => time(),
            ]);

            ReturnFactoryInfolist::where('p_id', $req_data['id'])->update([
                'is_del' => 2,
                'del_at' => time(),
            ]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '删除失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '删除成功']);
    }

    /**
     * 审核成功
     */
    public function doauditsuccess(Request $request)
    {
        $p_id = $request->p_id;
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        $goods_style_ids = $request->goods_style_ids;
        $goods_style_ids = is_array($goods_style_ids) ? $ids : (is_array(json_decode($goods_style_ids, true)) ? json_decode($goods_style_ids, true) : []);

        $goods_category_ids = $request->goods_category_ids;
        $goods_category_ids = is_array($goods_category_ids) ? $goods_category_ids : (is_array(json_decode($goods_category_ids, true)) ? json_decode($goods_category_ids, true) : []);

        if (count($ids) == 0 && count($goods_style_ids) == 0 && count($goods_category_ids) == 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        // 待操作的明细
        if (count($goods_category_ids) > 0) {
            $infolist = ReturnFactoryInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('goods_category_id', $goods_category_ids)->get()->toArray();
        } else {
            if (count($goods_style_ids) > 0) {
                $infolist = ReturnFactoryInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('goods_style_id', $goods_style_ids)->get()->toArray();
            } else {
                $infolist = ReturnFactoryInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('id', $ids)->get()->toArray();
            }
        }

        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                // 更新明细
                ReturnFactoryInfolist::where(['id' => $id, 'cp_id' => $cp_id])->update(['audit_status' => 2, 'audit_success_count' => $info['count'], 'audit_at' => time()]);

                //旧料库存更新为返厂
                Stock::where('id', $info['stock_id'])->update(['stock_status' => 5]);

                // 明细审核状态
                $audit_status_count = ReturnFactoryInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'audit_status' => 1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }
                // 返厂单审核成功数
                ReturnFactory::where(['id' => $info['p_id'], 'cp_id' => $cp_id])->increment('audit_success_count', $info['count'], ['audit_status' => $audit_status]);

                // 成功添加到总库存
                unset($info['id']);
                TotalStock::create($info);

                //日志
                Log::create([
                    'cp_id' => $cp_id,
                    'store_id' => $info['store_id'],
                    'start_store_id' => $info['start_store_id'],
                    'target_store_id' => $info['target_store_id'],
                    'order_sncode' => $info['order_sncode'],
                    'goods_category_id' => $info['goods_category_id'],
                    'piece_weight' => $info['piece_weight'],
                    'stock_type' => $info['stock_type'],
                    'count' => $info['count'],
                    'cf_no' => $info['cf_no'],
                    'log_type' => 6,
                    'create_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                ]);
            }

            $this->saveReturnStatus($cp_id, $p_id);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '审核成功']);
    }

    /**
     * 审核取消
     */
    public function doauditcancel(Request $request)
    {

        $p_id = $request->p_id;
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        $goods_style_ids = $request->goods_style_ids;
        $goods_style_ids = is_array($goods_style_ids) ? $ids : (is_array(json_decode($goods_style_ids, true)) ? json_decode($goods_style_ids, true) : []);

        $goods_category_ids = $request->goods_category_ids;
        $goods_category_ids = is_array($goods_category_ids) ? $goods_category_ids : (is_array(json_decode($goods_category_ids, true)) ? json_decode($goods_category_ids, true) : []);

        if (count($ids) == 0 && count($goods_style_ids) == 0 && count($goods_category_ids) == 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        if (count($goods_category_ids) > 0) {
            $infolist = ReturnFactoryInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('goods_category_id', $goods_category_ids)->get()->toArray();
        } else {
            if (count($goods_style_ids) > 0) {
                $infolist = ReturnFactoryInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('goods_style_id', $goods_style_ids)->get()->toArray();
            } else {
                $infolist = ReturnFactoryInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('id', $ids)->get()->toArray();
            }
        }

        $stockIds = array_column($infolist, 'stock_id');
        $stockList = Stock::query()
            ->where(['cp_id' => $cp_id])
            ->whereIn('id', $stockIds)
            ->get()
            ->pluck(null, 'id')
            ->toArray();

        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                ReturnFactoryInfolist::where(['id' => $id, 'cp_id' => $cp_id])->update(['audit_status' => 3, 'audit_failed_count' => $info['count'], 'audit_at' => time()]);
                $audit_status_count = ReturnFactoryInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'audit_status' => 1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }
                // 审核取消数
                ReturnFactory::query()->where(['id' => $info['p_id'], 'cp_id' => $cp_id])->increment('audit_failed_count', $info['count'], ['audit_status' => $audit_status]);

                // 取消退回库存
                $stock = $stockList[$info['stock_id']] ?? [];
                //旧料库存更新为在库
                if (!empty($stock)) {
                    $stockData = $this->checkReturn($stock, $info, true);
                    $stockData['stock_status'] = 1;
                    $stockData['update_at'] = time();
                    $stockData['audit_status'] = 3;
                    Stock::query()
                        ->where('id', $info['stock_id'])
                        ->where('cp_id', $cp_id)
                        ->where('store_id', $info['start_store_id'])
                        ->update($stockData);
                }


                //日志
                Log::create([
                    'cp_id' => $cp_id,
                    'store_id' => $info['store_id'],
                    'start_store_id' => $info['start_store_id'],
                    'target_store_id' => $info['target_store_id'],
                    'order_sncode' => $info['order_sncode'],
                    'goods_category_id' => $info['goods_category_id'],
                    'piece_weight' => $info['piece_weight'],
                    'stock_type' => $info['stock_type'],
                    'count' => $info['count'],
                    'cf_no' => $info['cf_no'],
                    'log_type' => 7,
                    'create_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                ]);
            }

            $this->saveReturnStatus($cp_id, $p_id);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核取消操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '审核取消成功']);
    }

    /**
     * 审核成功
     */
    public function doauditsuccessmore(Request $request)
    {
        $p_ids = $request->p_ids;

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        //查询子订单详情
        $list2_query = ReturnFactoryInfolist::whereIN('p_id',$p_ids);
        $list2_query->where(['audit_status'=>1,'cp_id' => $cp_id]);
        $ids = $list2_query->pluck('id')->all();


        if (count($ids) == 0 ) {
            return response()->json(['code' => '001', 'msg' => '没有可操作的数据']);
        }

        // 待操作的明细
        $infolist = ReturnFactoryInfolist::where(['cp_id' => $cp_id, 'audit_status' => 1])->whereIn('id', $ids)->get()->toArray();

        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                // 更新明细
                ReturnFactoryInfolist::where(['id' => $id, 'cp_id' => $cp_id])->update(['audit_status' => 2, 'audit_success_count' => $info['count'], 'audit_at' => time()]);

                //旧料库存更新为返厂
                Stock::where('id', $info['stock_id'])->update(['stock_status' => 5]);

                // 明细审核状态
                $audit_status_count = ReturnFactoryInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'audit_status' => 1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }
                // 返厂单审核成功数
                ReturnFactory::where(['id' => $info['p_id'], 'cp_id' => $cp_id])->increment('audit_success_count', $info['count'], ['audit_status' => $audit_status]);

                // 成功添加到总库存
                unset($info['id']);
                TotalStock::create($info);

                //日志
                Log::create([
                    'cp_id' => $cp_id,
                    'store_id' => $info['store_id'],
                    'start_store_id' => $info['start_store_id'],
                    'target_store_id' => $info['target_store_id'],
                    'order_sncode' => $info['order_sncode'],
                    'goods_category_id' => $info['goods_category_id'],
                    'piece_weight' => $info['piece_weight'],
                    'stock_type' => $info['stock_type'],
                    'count' => $info['count'],
                    'cf_no' => $info['cf_no'],
                    'log_type' => 6,
                    'create_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                ]);
            }

            // 检查是否全部审核完成
            $this->saveReturnStatus($cp_id, $p_ids);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '审核成功']);
    }

    /**
     * 审核取消
     */
    public function doauditcancelmore(Request $request)
    {
        $p_ids = $request->p_ids;

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        //查询子订单详情
        $list2_query = ReturnFactoryInfolist::whereIN('p_id',$p_ids);
        $list2_query->where(['audit_status'=>1,'cp_id' => $cp_id]);
        $ids = $list2_query->pluck('id')->all();

        if (count($ids) == 0 ) {
            return response()->json(['code' => '001', 'msg' => '没有可操作的数据']);
        }

        $infolist = ReturnFactoryInfolist::where([ 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('id', $ids)->get()->toArray();

        $stockIds = array_column($infolist, 'stock_id');
        $stockList = Stock::query()
            ->where(['cp_id' => $cp_id])
            ->whereIn('id', $stockIds)
            ->get()
            ->pluck(null, 'id')
            ->toArray();
        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                ReturnFactoryInfolist::where(['id' => $id, 'cp_id' => $cp_id])->update(['audit_status' => 3, 'audit_failed_count' => $info['count'], 'audit_at' => time()]);
                $audit_status_count = ReturnFactoryInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'audit_status' => 1])->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }
                // 审核取消数
                ReturnFactory::where(['id' => $info['p_id'], 'cp_id' => $cp_id])->increment('audit_failed_count', $info['count'], ['audit_status' => $audit_status]);
                // 取消退回库存
                $stock = $stockList[$info['stock_id']] ?? [];

                //旧料库存更新为在库
                if (!empty($stock)) {
                    $stockData = $this->checkReturn($stock, $info, true);
                    $stockData['stock_status'] = 1;
                    $stockData['update_at'] = time();
                    $stockData['audit_status'] = 3;
                    Stock::query()
                        ->where('id', $info['stock_id'])
                        ->where('cp_id', $cp_id)
                        ->where('store_id', $info['start_store_id'])
                        ->update($stockData);
                }

                //日志
                Log::create([
                    'cp_id' => $cp_id,
                    'store_id' => $info['store_id'],
                    'start_store_id' => $info['start_store_id'],
                    'target_store_id' => $info['target_store_id'],
                    'order_sncode' => $info['order_sncode'],
                    'goods_category_id' => $info['goods_category_id'],
                    'piece_weight' => $info['piece_weight'],
                    'stock_type' => $info['stock_type'],
                    'count' => $info['count'],
                    'cf_no' => $info['cf_no'],
                    'log_type' => 7,
                    'create_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                ]);
            }

            // 检查是否全部审核完成
            $this->saveReturnStatus($cp_id, $p_ids);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核取消操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '审核取消成功']);
    }



    /**
 * 计算返厂商品的库存数据
 *
 * 此方法用于根据原始库存和返厂信息，计算更新后的库存数据。
 * 包括数量、重量、价格等各项指标，并根据是否新增(isAdd)来决定是增加还是减少库存。
 *
 * @param array $stock 原始库存信息
 * @param array $return 返厂信息
 * @param bool $isAdd 是否为增加操作，默认为true(增加)，false表示减少
 * @param int $is_new_stock 是否为新库存记录，默认为0(不是新记录)
 * @return array 返回更新后的库存数据
 */
    protected function checkReturn($stock, $return, $isAdd = true, $is_new_stock = 0)
    {
        $stockData = []; // 存储更新后的库存数据

        // 获取返厂数量，默认为0
        $count = $return['count'] ?? 0;

        // 计算每件商品的各项属性值（保留相应精度）
        $netglod_weight_new = $stock['netglod_weight_new'] > 0 ? (bcdiv($stock['netglod_weight_new'], $stock['count'], 4)) : 0;
        $netglod_weight = $stock['netglod_weight'] > 0 ? (bcdiv($stock['netglod_weight'], $stock['count'], 4)) : 0;
        $piece_weight_new = $stock['piece_weight_new'] > 0 ? (bcdiv($stock['piece_weight_new'], $stock['count'], 4)) : 0;
        $piece_weight = $stock['piece_weight'] > 0 ? (bcdiv($stock['piece_weight'], $stock['count'], 4)) : 0;
        $old_recovery_price = $stock['old_recovery_price'] > 0 ? (bcdiv($stock['old_recovery_price'], $stock['count'], 2)) : 0;
        $exchange_amount = $stock['exchange_amount'] > 0 ? (bcdiv($stock['exchange_amount'], $stock['count'], 2)) : 0;
        $valuations = $stock['valuations'] > 0 ? (bcdiv($stock['valuations'], $stock['piece_weight'], 2)) : 0;

        // 如果不是新库存记录
        if ($is_new_stock == 0) {
            $stock['total_netglod_weight'] = $stock['netglod_weight'];

            if ($isAdd == true) {
                if($piece_weight_new == 0 || $piece_weight == 0)
                {
                    //只有删除和取消审核的场景涉及
                    //旧料老的库存清空了，所以单重计算有问题需要直接取调拨单的单重
                    $piece_weight_new = $return['piece_weight_new'] > 0 ? (bcdiv($return['piece_weight_new'], $return['count'], 4)) : 0;
                    $piece_weight = $return['piece_weight'] > 0 ? (bcdiv($return['piece_weight'], $return['count'], 4)) : 0;
                }

                if($exchange_amount == 0)
                {
                    //取消和删除的时候换换金额计算有问题，需要直接取调拨单的换金额
                    $exchange_amount = $return['exchange_amount'] > 0 ? (bcdiv($return['exchange_amount'], $return['count'], 2)) : 0;
                }

                // 增加库存操作
                $stockData['count'] = $stock['count'] + $count;

                // 查询该类别的旧料是否按克计价
                $is_gram = GoodsCategory::query()
                    ->where(['is_del' => 1, 'id' => $stock['goods_category_id']])
                    ->value('is_gram') ?? 0;

                // 准备增量数据用于计算总成本
                $incr['total_netglod_weight'] = $netglod_weight * $count;
                $incr['total_cost_fee'] = $return['netglod_weight'];

                // 调用服务计算新的总成本、金价和件成本
                list($total_cost_fee, $costglod_price, $piececost_fee) = (new Goods())->incrTotalCost($stock, $incr, $is_gram);

                $stockData['total_cost_fee'] = $total_cost_fee;
                $stockData['costglod_price'] = $costglod_price;
                $stockData['piececost_fee'] = $piececost_fee;
            } else {
                // 减少库存操作
                $stockData['count'] = $stock['count'] - $count;

                // 准备扣减数据用于计算总成本
                $deduction['total_netglod_weight'] = $netglod_weight * $count;

                // 调用服务计算扣除的成本和剩余成本
                list($deduct_total_cost_fee, $remaining_cost_fee) = (new Goods())->deductTotalCost($stock, $deduction);

                $stockData['deduct_total_cost_fee'] = $deduct_total_cost_fee;
                $stockData['remaining_cost_fee'] = $remaining_cost_fee;
            }
        } else {
            // 新库存记录直接设置数量
            $stockData['count'] = $count;
        }

        // 根据更新后的数量重新计算各项重量和价值
        $stockData['netglod_weight'] = bcmul($netglod_weight, $stockData['count'], 3);
        $stockData['netglod_weight_new'] = bcmul($netglod_weight_new, $stockData['count'], 3);
        $stockData['piece_weight'] = bcmul($piece_weight, $stockData['count'], 3);
        $stockData['piece_weight_new'] = bcmul($piece_weight_new, $stockData['count'], 3);

        // 计算回收价格、换货金额和估值（四舍五入）
        $stockData['old_recovery_price'] = round(bcmul($old_recovery_price, $stockData['count']));
        $stockData['exchange_amount'] = round(bcmul($exchange_amount, $stockData['count']));
        $stockData['valuations'] = round(bcmul($valuations, $stockData['piece_weight']));

        return $stockData;
    }

    /**
     * 更新张主订单状态
     * @param $cp_id
     * @param $p_id
     * @return true
     */
    protected function saveReturnStatus($cp_id, $p_id)
    {
        $p_ids = is_array($p_id) ? $p_id : [$p_id];
        $count = ReturnFactoryInfolist::query()
            ->where(['cp_id' => $cp_id, 'audit_status' => 5])
            ->whereIn('p_id', $p_ids)
            ->count();
        if ($count == 0) {
            ReturnFactory::query()
                ->where(['cp_id' => $cp_id])
                ->whereIn('id', $p_ids)
                ->update(['audit_status' => 3]);
        }

        return true;
    }

}
